
from fastapi import APIRouter
from core.config import response_body,mongo_engine
from pydantic import BaseModel
from datetime import datetime
router = APIRouter(prefix='/history')

mongo_client=mongo_engine["tools-simon"]
history_collection=mongo_client['history']


class HistorySearchModel(BaseModel):
    id: int=None
    year: int=None
    action: str=None
    tags: list[str]=None
    create_at: datetime=None
    update_at: datetime=None

@router.post('/find_history_action',summary='查询历史事件')
async def get_history_action(search:HistorySearchModel):
    """
    查询历史事件
    :param query: 查询字符串
    :param page_size: 每页数量
    :param page_num: 页码
    :param time_range: 时间范围
    :return: 历史事件列表
    """
    search_dict=search.model_dump()
    print(search_dict)
    query={}
    for key,value in search_dict.items():
        if value is not None:
            query[key]=value
        if key=='action':
            if value is not None:
                query[key]={'$regex':value}

    result=list(history_collection.find(query,{'_id':0}))
    response_body['msg']='分页过滤查询'
    response_body['data'] = {'result':result,'total':len(result)}
    return response_body

# 添加历史事件
class HistoryActionModel(BaseModel):
    year: int
    action: str
    tags: list[str]=[]

@router.post("/history_action", summary="添加历史事件")
async def add_history_action(history: HistoryActionModel):
    """
    添加历史事件
    """
    history_action=history.model_dump()
    history_action['create_at']=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    history_action['update_at']=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    count=history_collection.count_documents({})
    history_action['id']=count+1
    result=history_collection.insert_one(history_action)
    response_body['msg'] = '添加成功'
    response_body['data'] = {'result':str(result.inserted_id)}
    return response_body
